<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <meta name="keywords" content="Hexo Theme Keep">
    <meta name="description" content="宋标的个人博客">
    <meta name="author" content="宋标">
	<meta name="referrer" content="no-referrer"/>
    
    <title>
        
            分布式锁设计 |
        
        宋标的blog
    </title>
    
<link rel="stylesheet" href="/css/style.css">

    <link rel="shortcut icon" href="/images/logo.svg">
    
<link rel="stylesheet" href="/css/font-awesome.min.css">

    <script id="hexo-configurations">
    let KEEP = window.KEEP || {};
    KEEP.hexo_config = {"hostname":"song_biao.gitee.io","root":"/","language":"zh-CN","path":"search.xml"};
    KEEP.theme_config = {"toc":{"enable":true,"number":true,"expand_all":true,"init_open":true},"style":{"primary_color":"#0066CC","avatar":"/images/avatar.svg","favicon":"/images/logo.svg","article_img_align":"left","left_side_width":"260px","content_max_width":"920px","hover":{"shadow":false,"scale":false},"first_screen":{"enable":true,"background_img":"/images/bg.svg","description":"while(alive()) study();"},"scroll":{"progress_bar":{"enable":false},"percent":{"enable":false}}},"local_search":{"enable":true,"preload":false},"code_copy":{"enable":false,"style":"default"},"pjax":{"enable":false},"lazyload":{"enable":false},"version":"3.4.5"};
    KEEP.language_ago = {"second":"%s 秒前","minute":"%s 分钟前","hour":"%s 小时前","day":"%s 天前","week":"%s 周前","month":"%s 个月前","year":"%s 年前"};
  </script>
<meta name="generator" content="Hexo 6.1.0"></head>


<body>
<div class="progress-bar-container">
    

    
</div>


<main class="page-container">

    

    <div class="page-main-content">

        <div class="page-main-content-top">
            <header class="header-wrapper">

    <div class="header-content">
        <div class="left">
            
            <a class="logo-title" href="/">
                宋标的blog
            </a>
        </div>

        <div class="right">
            <div class="pc">
                <ul class="menu-list">
                    
                        <li class="menu-item">
                            <a class=""
                               href="/"
                            >
                                首页
                            </a>
                        </li>
                    
                        <li class="menu-item">
                            <a class=""
                               href="/tags"
                            >
                                标签
                            </a>
                        </li>
                    
                        <li class="menu-item">
                            <a class=""
                               href="/categories"
                            >
                                分类
                            </a>
                        </li>
                    
                        <li class="menu-item">
                            <a class=""
                               href="/archives"
                            >
                                归档
                            </a>
                        </li>
                    
                    
                        <li class="menu-item search search-popup-trigger">
                            <i class="fas fa-search"></i>
                        </li>
                    
                </ul>
            </div>
            <div class="mobile">
                
                    <div class="icon-item search search-popup-trigger"><i class="fas fa-search"></i></div>
                
                <div class="icon-item menu-bar">
                    <div class="menu-bar-middle"></div>
                </div>
            </div>
        </div>
    </div>

    <div class="header-drawer">
        <ul class="drawer-menu-list">
            
                <li class="drawer-menu-item flex-center">
                    <a class=""
                       href="/">首页</a>
                </li>
            
                <li class="drawer-menu-item flex-center">
                    <a class=""
                       href="/tags">标签</a>
                </li>
            
                <li class="drawer-menu-item flex-center">
                    <a class=""
                       href="/categories">分类</a>
                </li>
            
                <li class="drawer-menu-item flex-center">
                    <a class=""
                       href="/archives">归档</a>
                </li>
            
        </ul>
    </div>

    <div class="window-mask"></div>

</header>


        </div>

        <div class="page-main-content-middle">

            <div class="main-content">

                
                    <div class="fade-in-down-animation">
    <div class="article-content-container">

        <div class="article-title">
            <span class="title-hover-animation">分布式锁设计</span>
        </div>

        
            <div class="article-header">
                <div class="avatar">
                    <img src="/images/avatar.svg">
                </div>
                <div class="info">
                    <div class="author">
                        <span class="name">宋标</span>
                        
                            <span class="author-label">Lv5</span>
                        
                    </div>
                    <div class="meta-info">
                        <div class="article-meta-info">
    <span class="article-date article-meta-item">
        <i class="fas fa-edit"></i>&nbsp;
        <span class="pc">2023-02-28 16:59:35</span>
        <span class="mobile">2023-02-28 16:59</span>
    </span>
    
        <span class="article-categories article-meta-item">
            <i class="fas fa-folder"></i>&nbsp;
            <ul>
                
                    <li>
                        <a href="/categories/%E5%88%86%E5%B8%83%E5%BC%8F/">分布式</a>&nbsp;
                    </li>
                
            </ul>
        </span>
    
    
        <span class="article-tags article-meta-item">
            <i class="fas fa-tags"></i>&nbsp;
            <ul>
                
                    <li>
                        <a href="/tags/%E9%94%81/">锁</a>&nbsp;
                    </li>
                
            </ul>
        </span>
    

    
    
    
    
</div>

                    </div>
                </div>
            </div>
        

        <div class="article-content markdown-body">
            <meta name="referrer" content="no-referrer" />

<h1 id="Redis分布式锁实现"><a href="#Redis分布式锁实现" class="headerlink" title="Redis分布式锁实现"></a>Redis分布式锁实现</h1><h2 id="1-代码实现"><a href="#1-代码实现" class="headerlink" title="1.代码实现"></a>1.代码实现</h2><p>每个方法对应一个案例，且说明了每个方法的漏洞逐步升级解决。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@author</span> songbiao</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@desc</span> 模拟分布式锁</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">DistributeLockStudy</span> &#123;</span><br><span class="line"></span><br><span class="line">	<span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="type">String</span> <span class="variable">LOCK</span> <span class="operator">=</span> <span class="string">&quot;lock&quot;</span>;</span><br><span class="line">	<span class="keyword">public</span> <span class="type">Jedis</span> <span class="variable">jedis</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Jedis</span>(<span class="string">&quot;127.0.0.1&quot;</span>, <span class="number">6379</span>);</span><br><span class="line"></span><br><span class="line">	<span class="comment">/**</span></span><br><span class="line"><span class="comment">	 *</span></span><br><span class="line"><span class="comment">	 * <span class="doctag">@param</span> workTime 占用锁时间</span></span><br><span class="line"><span class="comment">	 * <span class="doctag">@param</span> intervalTime 获得锁间隔时间</span></span><br><span class="line"><span class="comment">	 * <span class="doctag">@throws</span> InterruptedException</span></span><br><span class="line"><span class="comment">	 */</span></span><br><span class="line">	<span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">getLock1</span><span class="params">(<span class="type">long</span> workTime, <span class="type">long</span> intervalTime)</span> <span class="keyword">throws</span> InterruptedException &#123;</span><br><span class="line">		<span class="comment">// 存在漏洞: 当多个服务器同时走到这条语句，互斥就失效。</span></span><br><span class="line">		<span class="keyword">while</span> (jedis.exists(LOCK)) &#123;</span><br><span class="line">			System.out.println(Thread.currentThread().getName() + <span class="string">&quot;间隔秒: &quot;</span> + intervalTime);</span><br><span class="line">			TimeUnit.SECONDS.sleep(intervalTime);</span><br><span class="line">		&#125;</span><br><span class="line">		jedis.setex(LOCK, workTime, System.currentTimeMillis() + <span class="string">&quot;&quot;</span>);</span><br><span class="line">		System.out.println(Thread.currentThread().getName() + <span class="string">&quot; 获得锁&quot;</span>);</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">getLock2</span><span class="params">(<span class="type">long</span> workTime, <span class="type">long</span> intervalTime)</span> <span class="keyword">throws</span> InterruptedException &#123;</span><br><span class="line">		<span class="comment">// 解决了上述的漏洞，还存在一个问题，线程可重入</span></span><br><span class="line">		<span class="keyword">while</span> (jedis.setnx(LOCK, System.currentTimeMillis() + <span class="string">&quot;&quot;</span>) == <span class="number">0</span>) &#123;</span><br><span class="line">			System.out.println(Thread.currentThread().getName() + <span class="string">&quot;间隔秒: &quot;</span> + intervalTime);</span><br><span class="line">			TimeUnit.SECONDS.sleep(intervalTime);</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="comment">// 问题: 如果set后在这一步前宕机，将会导致死锁。</span></span><br><span class="line">		jedis.expire(LOCK, workTime);</span><br><span class="line">		System.out.println(Thread.currentThread().getName() + <span class="string">&quot; 获得锁&quot;</span>);</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="comment">/**</span></span><br><span class="line"><span class="comment">	 * lua脚本解决可重入和原子性问题</span></span><br><span class="line"><span class="comment">	 * <span class="doctag">@param</span> workTime</span></span><br><span class="line"><span class="comment">	 * <span class="doctag">@param</span> intervalTime</span></span><br><span class="line"><span class="comment">	 * <span class="doctag">@param</span> value 解决可重入</span></span><br><span class="line"><span class="comment">	 * <span class="doctag">@throws</span> InterruptedException</span></span><br><span class="line"><span class="comment">	 */</span></span><br><span class="line">	<span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">getLock3</span><span class="params">(String workTime, <span class="type">long</span> intervalTime, String value)</span> <span class="keyword">throws</span> InterruptedException &#123;</span><br><span class="line">		<span class="comment">// lua脚本解决了可重入和原子性的问题，很有一个隐患的问题，如果锁超时自动释放, 当前线程还没有完成任务，其它线程获得锁就会出现线程安全问题。</span></span><br><span class="line">		<span class="type">String</span> <span class="variable">lockScript</span> <span class="operator">=</span></span><br><span class="line">				<span class="string">&quot;local key = KEYS[1]\n&quot;</span> +</span><br><span class="line">				<span class="string">&quot;local requestId = KEYS[2]\n&quot;</span> +</span><br><span class="line">				<span class="string">&quot;local ttl = tonumber(KEYS[3])\n&quot;</span> +</span><br><span class="line">				<span class="string">&quot;local result = redis.call(&#x27;setnx&#x27;, key, requestId)\n&quot;</span> +</span><br><span class="line">				<span class="string">&quot;if result == 1 then\n&quot;</span> +</span><br><span class="line">				<span class="string">&quot;    redis.call(&#x27;expire&#x27;, key, ttl)\n&quot;</span> +</span><br><span class="line">				<span class="string">&quot;else\n&quot;</span> +</span><br><span class="line">				<span class="string">&quot;    result = -1;\n&quot;</span> +</span><br><span class="line">				<span class="string">&quot;    local value = redis.call(&#x27;get&#x27;, key)\n&quot;</span> +</span><br><span class="line">				<span class="string">&quot;    if (value == requestId) then\n&quot;</span> +</span><br><span class="line">				<span class="string">&quot;        result = 1;\n&quot;</span> +</span><br><span class="line">				<span class="string">&quot;        redis.call(&#x27;expire&#x27;, key, ttl)\n&quot;</span> +</span><br><span class="line">				<span class="string">&quot;    end\n&quot;</span> +</span><br><span class="line">				<span class="string">&quot;end\n&quot;</span> +</span><br><span class="line">				<span class="string">&quot;return result&quot;</span>;</span><br><span class="line">		<span class="type">String</span> <span class="variable">sha</span> <span class="operator">=</span> jedis.scriptLoad(lockScript);</span><br><span class="line">		<span class="keyword">while</span> ((Long)jedis.evalsha(sha, <span class="number">3</span>, LOCK, value, workTime) == -<span class="number">1</span>) &#123;</span><br><span class="line">			System.out.println(Thread.currentThread().getName() + <span class="string">&quot;间隔秒: &quot;</span> + intervalTime);</span><br><span class="line">			TimeUnit.SECONDS.sleep(intervalTime);</span><br><span class="line">		&#125;</span><br><span class="line">		System.out.println(Thread.currentThread().getName() + <span class="string">&quot; 获得锁&quot;</span>);</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="meta">@Test</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">Test</span><span class="params">()</span> <span class="keyword">throws</span> InterruptedException &#123;</span><br><span class="line">        <span class="keyword">for</span> (<span class="type">int</span> <span class="variable">i</span> <span class="operator">=</span> <span class="number">0</span>; i &lt; <span class="number">10</span>; i++) &#123;</span><br><span class="line">            <span class="type">String</span> <span class="variable">uuid</span> <span class="operator">=</span> UUID.randomUUID().toString() + <span class="string">&quot;&quot;</span>;</span><br><span class="line">            <span class="keyword">new</span> <span class="title class_">Thread</span>(<span class="keyword">new</span> <span class="title class_">Runnable</span>() &#123;</span><br><span class="line">                <span class="meta">@Override</span></span><br><span class="line">                <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">run</span><span class="params">()</span> &#123;</span><br><span class="line">                    <span class="keyword">try</span> &#123;</span><br><span class="line">                        <span class="keyword">new</span> <span class="title class_">DistributeLockStudy</span>().getLock3(<span class="string">&quot;60&quot;</span>, <span class="number">1</span>, uuid);</span><br><span class="line">                    &#125; <span class="keyword">catch</span> (InterruptedException e) &#123;</span><br><span class="line">                        e.printStackTrace();</span><br><span class="line">                    &#125;</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;).start();</span><br><span class="line">        &#125;</span><br><span class="line">        Thread.currentThread().join();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="2-锁续约"><a href="#2-锁续约" class="headerlink" title="2.锁续约"></a>2.锁续约</h2><p>解决锁超时业务代码还没有执行完的问题，自实现的锁续约代码。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br></pre></td><td class="code"><pre><span class="line">       <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">getLock4</span><span class="params">(String workTime, <span class="type">long</span> intervalTime, String value)</span> <span class="keyword">throws</span> InterruptedException &#123;</span><br><span class="line">	getLock3(workTime, intervalTime, value);</span><br><span class="line">	watch(Thread.currentThread(), Long.parseLong(workTime), LOCK, value);</span><br><span class="line">	<span class="comment">// 忙60秒钟</span></span><br><span class="line">	TimeUnit.SECONDS.sleep(<span class="number">60</span>);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 锁续约</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> workThread</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> workTimeSecond</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> key</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> value</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title function_">watch</span><span class="params">(Thread workThread, <span class="type">long</span> workTimeSecond, String key, String value)</span> &#123;</span><br><span class="line">	<span class="type">long</span> <span class="variable">base</span> <span class="operator">=</span> (<span class="type">long</span>) (workTimeSecond * (<span class="number">1.0</span> / <span class="number">3</span>));</span><br><span class="line">	<span class="type">AtomicLong</span> <span class="variable">timer</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">AtomicLong</span>(<span class="number">0</span>);</span><br><span class="line">	<span class="keyword">new</span> <span class="title class_">Thread</span>(<span class="keyword">new</span> <span class="title class_">Runnable</span>() &#123;</span><br><span class="line">		<span class="meta">@Override</span></span><br><span class="line">		<span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">run</span><span class="params">()</span> &#123;</span><br><span class="line">			<span class="keyword">while</span> (<span class="literal">true</span>) &#123;</span><br><span class="line">				<span class="keyword">try</span> &#123;</span><br><span class="line">					System.out.println(<span class="string">&quot;[监测持有锁线程] 计时器:&quot;</span> + timer.get());</span><br><span class="line">					TimeUnit.SECONDS.sleep(<span class="number">1</span>);</span><br><span class="line">					<span class="keyword">if</span> (workThread.isAlive() &amp;&amp; timer.addAndGet(<span class="number">1</span>) &gt; base) &#123;</span><br><span class="line">						<span class="type">long</span> <span class="variable">addTime</span> <span class="operator">=</span> jedis.ttl(LOCK) + workTimeSecond;</span><br><span class="line">						jedis.expire(LOCK, addTime);</span><br><span class="line">						System.out.println(<span class="string">&quot;[锁续约] 持有锁时间:&quot;</span> + jedis.ttl(LOCK));</span><br><span class="line">						timer.set(<span class="number">0</span>);</span><br><span class="line">					&#125; <span class="keyword">else</span> <span class="keyword">if</span> (!workThread.isAlive()) &#123;</span><br><span class="line">						Assert.isTrue(unlock(key, value), <span class="string">&quot;解锁失败!!&quot;</span>);</span><br><span class="line">						<span class="keyword">break</span>;</span><br><span class="line">					&#125;</span><br><span class="line">				&#125; <span class="keyword">catch</span> (InterruptedException e) &#123;</span><br><span class="line">					e.printStackTrace();</span><br><span class="line">				&#125;</span><br><span class="line">			&#125;</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;).start();</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="type">boolean</span> <span class="title function_">unlock</span><span class="params">(String key, String value)</span> &#123;</span><br><span class="line">	<span class="type">String</span> <span class="variable">unlockScript</span> <span class="operator">=</span></span><br><span class="line">			<span class="string">&quot;local key = KEYS[1]\n&quot;</span> +</span><br><span class="line">					<span class="string">&quot;local requestId = KEYS[2]\n&quot;</span> +</span><br><span class="line">					<span class="string">&quot;local value = redis.call(&#x27;get&#x27;, key)\n&quot;</span> +</span><br><span class="line">					<span class="string">&quot;if value == requestId then\n&quot;</span> +</span><br><span class="line">					<span class="string">&quot;    redis.call(&#x27;del&#x27;, key);\n&quot;</span> +</span><br><span class="line">					<span class="string">&quot;    return 1;\n&quot;</span> +</span><br><span class="line">					<span class="string">&quot;end\n&quot;</span> +</span><br><span class="line">					<span class="string">&quot;return -1&quot;</span>;</span><br><span class="line">	<span class="type">String</span> <span class="variable">sha</span> <span class="operator">=</span> jedis.scriptLoad(unlockScript);</span><br><span class="line">	System.out.println(<span class="string">&quot;释放锁:&quot;</span> + key);</span><br><span class="line">	<span class="keyword">return</span> (<span class="type">long</span>)jedis.evalsha(sha, <span class="number">2</span>, key, value) == <span class="number">1</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">   <span class="meta">@Test</span></span><br><span class="line">   <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">addLockTime</span><span class="params">()</span> <span class="keyword">throws</span> InterruptedException &#123;</span><br><span class="line">   </span><br><span class="line">           <span class="keyword">new</span> <span class="title class_">Thread</span>(<span class="keyword">new</span> <span class="title class_">Runnable</span>() &#123;</span><br><span class="line">               <span class="meta">@Override</span></span><br><span class="line">               <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">run</span><span class="params">()</span> &#123;</span><br><span class="line">                   <span class="type">DistributeLockStudy</span> <span class="variable">dlock</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">DistributeLockStudy</span>();</span><br><span class="line">                   <span class="keyword">try</span> &#123;</span><br><span class="line">                       dlock.getLock4(<span class="string">&quot;10&quot;</span>, <span class="number">1</span>, UUID.randomUUID().toString() + <span class="string">&quot;&quot;</span>);</span><br><span class="line">                   &#125; <span class="keyword">catch</span> (InterruptedException e) &#123;</span><br><span class="line">                       e.printStackTrace();</span><br><span class="line">                   &#125;</span><br><span class="line">               &#125;</span><br><span class="line">           &#125;).start();</span><br><span class="line">   </span><br><span class="line">           Thread.currentThread().join();</span><br><span class="line">   &#125;</span><br></pre></td></tr></table></figure>
<h2 id="3-RedLock"><a href="#3-RedLock" class="headerlink" title="3.RedLock"></a>3.RedLock</h2><p>事实上这类琐最大的缺点就是加锁时只作用在一个Redis节点上，即使Redis通过sentinel保证高可用，如果这个master节点由于某些原因发生了主从切换，那么就会出现锁丢失的情况：</p>
<ul>
<li>在Redis的master节点上拿到了锁；</li>
<li>但是这个加锁的key还没有同步到slave节点；</li>
<li>master故障，发生故障转移，slave节点升级为master节点；</li>
<li>导致锁丢失。</li>
</ul>
<p>正因为如此，Redis作者antirez基于分布式环境下提出了一种更高级的分布式锁的实现方式：Redlock。笔者认为，Redlock也是Redis所有分布式锁实现方式中唯一能让面试官高潮的方式。</p>
<p>Redlock实现<br>antirez提出的redlock算法大概是这样的：</p>
<p>在Redis的分布式环境中，我们假设有N个Redis master。这些节点完全互相独立，不存在主从复制或者其他集群协调机制。我们确保将在N个实例上使用与在Redis单实例下相同方法获取和释放锁。现在我们假设有5个Redis master节点，同时我们需要在5台服务器上面运行这些Redis实例，这样保证他们不会同时都宕掉。</p>
<p>为了取到锁，客户端应该执行以下操作:</p>
<ul>
<li>获取当前Unix时间，以毫秒为单位。</li>
<li>依次尝试从5个实例，使用相同的key和具有唯一性的value（例如UUID）获取锁。当向Redis请求获取锁时，客户端应该设置一个网络连接和响应超时时间，这个超时时间应该小于锁的失效时间。例如你的锁自动失效时间为10秒，则超时时间应该在5-50毫秒之间。这样可以避免服务器端Redis已经挂掉的情况下，客户端还在死死地等待响应结果。如果服务器端没有在规定时间内响应，客户端应该尽快尝试去另外一个Redis实例请求获取锁。</li>
<li>客户端使用当前时间减去开始获取锁时间（步骤1记录的时间）就得到获取锁使用的时间。当且仅当从大多数（N&#x2F;2+1，这里是3个节点）的Redis节点都取到锁，并且使用的时间小于锁失效时间时，锁才算获取成功。</li>
<li>如果取到了锁，key的真正有效时间等于有效时间减去获取锁所使用的时间（步骤3计算的结果）。</li>
<li>如果因为某些原因，获取锁失败（没有在至少N&#x2F;2+1个Redis实例取到锁或者取锁时间已经超过了有效时间），客户端应该在所有的Redis实例上进行解锁（即便某些Redis实例根本就没有加锁成功，防止某些节点获取到锁但是客户端没有得到响应而导致接下来的一段时间不能被重新获取锁）。</li>
</ul>
<p><strong>代码实现</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">static</span> <span class="keyword">class</span> <span class="title class_">RedLock</span> &#123;</span><br><span class="line">		<span class="keyword">public</span> <span class="keyword">final</span> <span class="keyword">static</span> RedissonRedLock RED_LOCK;</span><br><span class="line"></span><br><span class="line">		<span class="keyword">static</span> &#123;</span><br><span class="line">			<span class="type">Config</span> <span class="variable">config1</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Config</span>();</span><br><span class="line">			config1.useSingleServer().setAddress(<span class="string">&quot;redis://127.0.0.1:6379&quot;</span>);</span><br><span class="line">			<span class="type">RedissonClient</span> <span class="variable">redissonClient1</span> <span class="operator">=</span> Redisson.create(config1);</span><br><span class="line"></span><br><span class="line">			<span class="type">Config</span> <span class="variable">config2</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Config</span>();</span><br><span class="line">			config2.useSingleServer().setAddress(<span class="string">&quot;redis://127.0.0.1:6380&quot;</span>);</span><br><span class="line">			<span class="type">RedissonClient</span> <span class="variable">redissonClient2</span> <span class="operator">=</span> Redisson.create(config2);</span><br><span class="line"></span><br><span class="line">			<span class="type">Config</span> <span class="variable">config3</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Config</span>();</span><br><span class="line">			config3.useSingleServer().setAddress(<span class="string">&quot;redis://127.0.0.1:6381&quot;</span>);</span><br><span class="line">			<span class="type">RedissonClient</span> <span class="variable">redissonClient3</span> <span class="operator">=</span> Redisson.create(config3);</span><br><span class="line"></span><br><span class="line">			<span class="type">String</span> <span class="variable">resourceName</span> <span class="operator">=</span> <span class="string">&quot;REDLOCK_KEY&quot;</span>;</span><br><span class="line"></span><br><span class="line">			<span class="type">RLock</span> <span class="variable">lock1</span> <span class="operator">=</span> redissonClient1.getLock(resourceName);</span><br><span class="line">			<span class="type">RLock</span> <span class="variable">lock2</span> <span class="operator">=</span> redissonClient2.getLock(resourceName);</span><br><span class="line">			<span class="type">RLock</span> <span class="variable">lock3</span> <span class="operator">=</span> redissonClient3.getLock(resourceName);</span><br><span class="line">			<span class="comment">// 向3个redis实例尝试加锁</span></span><br><span class="line">			RED_LOCK = <span class="keyword">new</span> <span class="title class_">RedissonRedLock</span>(lock1, lock2, lock3);</span><br><span class="line">		&#125;</span><br><span class="line"></span><br><span class="line">		<span class="keyword">public</span> <span class="keyword">static</span> <span class="type">boolean</span> <span class="title function_">tryLock</span><span class="params">(<span class="type">long</span> waitTime, TimeUnit timeUnit)</span> &#123;</span><br><span class="line">			<span class="keyword">try</span> &#123;</span><br><span class="line">				<span class="comment">// isLock = redLock.tryLock();</span></span><br><span class="line">                <span class="comment">// waitTime时间内是否成功获得锁</span></span><br><span class="line">				<span class="keyword">return</span> RED_LOCK.tryLock(waitTime, timeUnit);</span><br><span class="line">			&#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">				e.printStackTrace();</span><br><span class="line">			&#125;</span><br><span class="line">			<span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line">		&#125;</span><br><span class="line"></span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> &#123;</span><br><span class="line">		<span class="keyword">for</span> (<span class="type">int</span> <span class="variable">i</span> <span class="operator">=</span> <span class="number">0</span>; i &lt; <span class="number">5</span>; i++) &#123;</span><br><span class="line">			<span class="keyword">new</span> <span class="title class_">Thread</span>(() -&gt; &#123;</span><br><span class="line">				<span class="keyword">while</span> (<span class="literal">true</span>) &#123;</span><br><span class="line">					<span class="keyword">try</span> &#123;</span><br><span class="line">						<span class="comment">// 默认30秒租约时间，redisson自动续约</span></span><br><span class="line">						<span class="keyword">if</span> (RedLock.tryLock(<span class="number">500</span>, TimeUnit.MILLISECONDS)) &#123;</span><br><span class="line">							System.out.println(Thread.currentThread().getName() + <span class="string">&quot; 获得锁&quot;</span>);</span><br><span class="line">							<span class="comment">// do something...</span></span><br><span class="line">							TimeUnit.SECONDS.sleep(<span class="number">5</span>);</span><br><span class="line">							<span class="keyword">break</span>;</span><br><span class="line">						&#125;</span><br><span class="line">						System.out.println(Thread.currentThread().getName() + <span class="string">&quot; 等待锁&quot;</span>);</span><br><span class="line">						TimeUnit.MILLISECONDS.sleep(<span class="number">500</span>);</span><br><span class="line">					&#125; <span class="keyword">catch</span> (InterruptedException e) &#123;</span><br><span class="line">						e.printStackTrace();</span><br><span class="line">					&#125;</span><br><span class="line">				&#125;</span><br><span class="line">				System.out.println(Thread.currentThread().getName() + <span class="string">&quot; 业务执行完毕..&quot;</span>);</span><br><span class="line">				RedLock.RED_LOCK.unlock();</span><br><span class="line">			&#125;).start();</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br></pre></td></tr></table></figure>
<p>参考：<a class="link"   target="_blank" rel="noopener" href="https://www.jianshu.com/p/7e47a4503b87" >https://www.jianshu.com/p/7e47a4503b87<i class="fas fa-external-link-alt"></i></a></p>

        </div>

        

        
            <ul class="post-tags-box">
                
                    <li class="tag-item">
                        <a href="/tags/%E9%94%81/">#锁</a>&nbsp;
                    </li>
                
            </ul>
        

        
            <div class="article-nav">
                
                    <div class="article-prev">
                        <a class="prev"
                           rel="prev"
                           href="/2023/03/01/Spring%E7%9A%84%E4%BA%8B%E5%8A%A1%E4%BC%A0%E6%92%AD%E6%9C%BA%E5%88%B6/"
                        >
                            <span class="left arrow-icon flex-center">
                              <i class="fas fa-chevron-left"></i>
                            </span>
                            <span class="title flex-center">
                                <span class="post-nav-title-item">Spring的事务传播机制</span>
                                <span class="post-nav-item">上一篇</span>
                            </span>
                        </a>
                    </div>
                
                
                    <div class="article-next">
                        <a class="next"
                           rel="next"
                           href="/2023/02/23/bean%E7%9A%84%E7%94%9F%E5%91%BD%E5%91%A8%E6%9C%9F/"
                        >
                            <span class="title flex-center">
                                <span class="post-nav-title-item">bean的生命周期</span>
                                <span class="post-nav-item">下一篇</span>
                            </span>
                            <span class="right arrow-icon flex-center">
                              <i class="fas fa-chevron-right"></i>
                            </span>
                        </a>
                    </div>
                
            </div>
        

        
            <div class="comment-container">
                <div class="comments-container">
    <div id="comment-anchor"></div>
    <div class="comment-area-title">
        <i class="fas fa-comments">&nbsp;评论</i>
    </div>
    

        
            
    <div class="valine-container">
        <script 
                src="//cdn.jsdelivr.net/npm/valine@latest/dist/Valine.min.js"></script>
        <div id="vcomments"></div>
        <script >
            function loadValine() {
                new Valine({
                    el: '#vcomments',
                    appId: 'GaPFQduCGtJWQ2Cmma9jEfx1-gzGzoHsz',
                    appKey: 'h9IWwxU3RWqBFCD4CqERkpuv',
                    meta: ['nick', 'mail', 'link'],
                    avatar: 'wavatar',
                    enableQQ: true,
                    placeholder: '',
                    lang: 'zh-CN'.toLowerCase()
                });

                function getAuthor(language) {
                    switch (language) {
                        case 'en':
                            return 'Author';
                        case 'zh-CN':
                            return '博主';
                        default:
                            return 'Master';
                    }
                }

                // Add "Author" identify
                const getValineDomTimer = setInterval(() => {
                    const vcards = document.querySelectorAll('#vcomments .vcards .vcard');
                    if (vcards.length > 0) {
                        let author = '宋标';

                        if (author) {
                            for (let vcard of vcards) {
                                const vnick_dom = vcard.querySelector('.vhead .vnick');
                                const vnick = vnick_dom.innerHTML;
                                if (vnick === author) {
                                    vnick_dom.innerHTML = `${vnick} <span class="author">${getAuthor(KEEP.hexo_config.language)}</span>`
                                }
                            }
                        }
                        clearInterval(getValineDomTimer);
                    } else {
                        clearInterval(getValineDomTimer);
                    }
                }, 2000);
            }

            if ('false') {
                const loadValineTimeout = setTimeout(() => {
                    loadValine();
                    clearTimeout(loadValineTimeout);
                }, 1000);
            } else {
                window.addEventListener('DOMContentLoaded', loadValine);
            }
        </script>
    </div>



        
    
</div>

            </div>
        
    </div>
</div>


                
            </div>

        </div>

        <div class="page-main-content-bottom">
            <footer class="footer">
    <div class="info-container">
        <div class="copyright-info info-item">
            &copy;
            
              <span>2020</span>
              -
            
            2023&nbsp;<i class="fas fa-heart icon-animate"></i>&nbsp;<a href="/">宋标</a>
        </div>
        
        <div class="theme-info info-item">
            由 <a target="_blank" href="https://hexo.io">Hexo</a> 驱动&nbsp;|&nbsp;主题&nbsp;<a class="theme-version" target="_blank" href="https://github.com/XPoet/hexo-theme-keep">Keep v3.4.5</a>
        </div>
        
        
    </div>
</footer>

        </div>
    </div>

    
        <div class="post-tools">
            <div class="post-tools-container">
    <ul class="tools-list">
        <!-- TOC aside toggle -->
        
            <li class="tools-item page-aside-toggle">
                <i class="fas fa-outdent"></i>
            </li>
        

        <!-- go comment -->
        
            <li class="go-comment">
                <i class="fas fa-comment"></i>
            </li>
        
    </ul>
</div>

        </div>
    

    <div class="right-bottom-side-tools">
        <div class="side-tools-container">
    <ul class="side-tools-list">
        <li class="tools-item tool-font-adjust-plus flex-center">
            <i class="fas fa-search-plus"></i>
        </li>

        <li class="tools-item tool-font-adjust-minus flex-center">
            <i class="fas fa-search-minus"></i>
        </li>

        <li class="tools-item tool-expand-width flex-center">
            <i class="fas fa-arrows-alt-h"></i>
        </li>

        <li class="tools-item tool-dark-light-toggle flex-center">
            <i class="fas fa-moon"></i>
        </li>

        <!-- rss -->
        

        
            <li class="tools-item tool-scroll-to-top flex-center">
                <i class="fas fa-arrow-up"></i>
            </li>
        

        <li class="tools-item tool-scroll-to-bottom flex-center">
            <i class="fas fa-arrow-down"></i>
        </li>
    </ul>

    <ul class="exposed-tools-list">
        <li class="tools-item tool-toggle-show flex-center">
            <i class="fas fa-cog fa-spin"></i>
        </li>
        
    </ul>
</div>

    </div>

    
        <aside class="page-aside">
            <div class="post-toc-wrap">
    <div class="post-toc">
        <ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#Redis%E5%88%86%E5%B8%83%E5%BC%8F%E9%94%81%E5%AE%9E%E7%8E%B0"><span class="nav-number">1.</span> <span class="nav-text">Redis分布式锁实现</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#1-%E4%BB%A3%E7%A0%81%E5%AE%9E%E7%8E%B0"><span class="nav-number">1.1.</span> <span class="nav-text">1.代码实现</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-%E9%94%81%E7%BB%AD%E7%BA%A6"><span class="nav-number">1.2.</span> <span class="nav-text">2.锁续约</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#3-RedLock"><span class="nav-number">1.3.</span> <span class="nav-text">3.RedLock</span></a></li></ol></li></ol>
    </div>
</div>
        </aside>
    

    <div class="image-viewer-container">
    <img src="">
</div>


    
        <div class="search-pop-overlay">
    <div class="popup search-popup">
        <div class="search-header">
          <span class="search-input-field-pre">
            <i class="fas fa-keyboard"></i>
          </span>
            <div class="search-input-container">
                <input autocomplete="off"
                       autocorrect="off"
                       autocapitalize="off"
                       placeholder="搜索..."
                       spellcheck="false"
                       type="search"
                       class="search-input"
                >
            </div>
            <span class="popup-btn-close">
                <i class="fas fa-times"></i>
            </span>
        </div>
        <div id="search-result">
            <div id="no-result">
                <i class="fas fa-spinner fa-pulse fa-5x fa-fw"></i>
            </div>
        </div>
    </div>
</div>

    

</main>




<script src="/js/utils.js"></script>

<script src="/js/main.js"></script>

<script src="/js/header-shrink.js"></script>

<script src="/js/back2top.js"></script>

<script src="/js/dark-light-toggle.js"></script>



    
<script src="/js/local-search.js"></script>







<div class="post-scripts">
    
        
<script src="/js/left-side-toggle.js"></script>

<script src="/js/libs/anime.min.js"></script>

<script src="/js/toc.js"></script>

    
</div>



</body>
</html>
